import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models

# 加载MNIST数据集
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# 将像素值归一化到0-1范围
train_images, test_images = train_images / 255.0, test_images / 255.0

# 因为MNIST的图像是28x28，我们需要将其展开成784维的向量
train_images = train_images.reshape((60000, 28 * 28))
test_images = test_images.reshape((10000, 28 * 28))

# 构建一个简单的MLP模型
model = models.Sequential([
    layers.Dense(512, activation='relu', input_shape=(28 * 28,)),
    layers.Dropout(0.2),
    layers.Dense(10, activation='softmax')
])

# 编译模型
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# 训练模型
model.fit(train_images, train_labels, epochs=5, batch_size=32, validation_split=0.1)

# 评估模型
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
print('\nTest accuracy:', test_acc)

# 使用模型进行预测
predictions = model.predict(test_images)

# 打印预测结果
print("Predictions for first 5 images:")
print(np.argmax(predictions[:5], axis=1))

model.save('mnist_model.h5')

